package com.wushi.lenovo.asia5b.app_di.other.presenter;

import android.app.Activity;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;

import com.mvp.base.BaseAppCompatActivity;
import com.mvp.base.BaseApplication;
import com.mvp.base.BasePresenter;
import com.mvp.base.NetParams;
import com.mvp.common.LocalManageUtil;
import com.mvp.helper.WCallBack;
import com.mvp.utils.ResString;
import com.mvp.utils.ToastUtil;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.BuildConfig;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_di.other.mvpview.MainActivityView;
import com.wushi.lenovo.asia5b.app_http.ApiService;
import com.wushi.lenovo.asia5b.app_http.TopupService;
import com.wushi.lenovo.asia5b.app_model.good.TaokouModel;
import com.wushi.lenovo.asia5b.app_model.other.CacheType;
import com.wushi.lenovo.asia5b.app_model.other.CategoryModel;
import com.wushi.lenovo.asia5b.app_model.other.UpdateModel;
import com.wushi.lenovo.asia5b.app_model.other.UserInfo;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.TaokouDialog;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.UpdateDialog;
import com.wushi.lenovo.asia5b.app_utils.helper.CacheHelper;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;


/**
 * Created by zhangyuncai on 2019/3/9.
 */
public class MainActivityPresenter extends BasePresenter<MainActivityView> {

    ApiService apiService;
    TopupService topupService;
    private Disposable clipChangeDis;

    @Inject
    public MainActivityPresenter(ApiService apiService, TopupService topupService) {
        this.apiService = apiService;
        this.topupService = topupService;
    }

    /**
     * 监听剪切板,延迟3S开始监听
     *
     * @param activity
     */
    public void registClip(Activity activity) {
        Timber.d("--->>>>>>>>---Build.VERSION.SDK_INT:" + Build.VERSION.SDK_INT);
        //安卓9.0以下可以继续后台监听剪切板
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {

            final ClipboardManager cm = (ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
            cm.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener() {
                @Override
                public void onPrimaryClipChanged() {
                    BaseApplication.parseCm();
                }
            });
        }
        //每10S加载淘口令
        clipChangeDis = Observable.intervalRange(0, 5, 0, 2, TimeUnit.SECONDS)
                .observeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    BaseApplication.parseCm();
                }, throwable -> {

                });
    }

    /**
     * 根据监听到的url地址获取商品详情数据
     * todo 成功获取淘口令数据后,展示商品内容
     *
     * @param taokouUrl
     */
    public void getProductByKouling(String taokouUrl) {
        if (clipChangeDis != null && !clipChangeDis.isDisposed()) {
            clipChangeDis.dispose();
        }
        Map<String, Object> map = MapHelper.newHashMap();
        map.put("prod_key", taokouUrl + "");
        map.put("lang", LocalManageUtil.getAppLanguage() + "");
        int countryId = UserInfo.getCountryId();
        if (countryId <= 0) {
            countryId = 4;
        }
        map.put("country_id", countryId);
        map.put("member_id", UserInfo.getMemberId());
        NetParams netParams = new NetParams(false, false, false);
        if (BuildConfig.DEBUG && false) {
            netParams = new NetParams();
            netParams.setShowTag("加载淘口令商品...");
        }
        baseSubscribe(apiService.getProductByKouling(map),
                netParams,
                resultModel -> {
                    if (resultModel.isSuccess()) {
                        TaokouModel taokouModel = resultModel.getData();
                        if (taokouModel != null) {
                            TaokouDialog.showTaokouDialog(taokouModel);
                        }
                    } else {

                        if (resultModel.getResult() == 10 && resultModel.getData() != null) {
                            ToastUtil.showToast(resultModel.getMsg());
                        }

                    }
                }
        );
    }


    /**
     * 获取国家列表数据
     *
     * @param activity
     */
    public void delayData(BaseAppCompatActivity activity) {
        //延时两秒加载数据
        Observable.timer(2, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(aLong -> {
                    checkUpdate(activity, false);
                    CacheHelper.getCountrys(null, CacheType.NET);
                    getCreditMin();

                });

    }

    /**
     * 获取左菜单栏列表
     *
     * @return
     */
    public List<CategoryModel> getFirstCategorys() {
        return CacheHelper.getCategorys(new WCallBack<List<CategoryModel>>() {
            @Override
            public void callback(List<CategoryModel> categoryModels) {
                getView().getFirstCategorysResult(categoryModels);
            }
        });
    }

    /**
     * 获取最低充值
     */
    public void getCreditMin() {
        CacheHelper.getCreditMin(null, CacheType.NET);
    }

    /**
     * 版本检测更新
     *
     * @param activity
     */
    public void checkUpdate(Activity activity, boolean isToast) {
        baseSubscribe(apiService.getAppInfo("android", LocalManageUtil.getAppLanguage()),
                new NetParams(false, false, false),
                resultModel -> {
                    if (resultModel.isSuccess() && resultModel.getData() != null && resultModel.getData().size() > 0) {
                        UpdateModel data = resultModel.getData().get(0);
                        if (data != null) {

                            try {
                                PackageInfo packageInfo = getPackageInfo(activity);
                                long netBuild = Long.parseLong(data.getBuild());
                                long localBuild = 0;
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                                    localBuild = packageInfo.getLongVersionCode();
                                } else {
                                    localBuild = packageInfo.versionCode;
                                }
                                if (netBuild > localBuild) {
                                    if (BuildConfig.appType == 0) {
                                        data.setForce_update("1");
                                    }
                                    new UpdateDialog(data, activity).show();
                                } else if (isToast) {
                                    ToastUtil.showToast(ResString.get(R.string.Update_ISNEW));
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }


    /**
     * 获取包名信息
     *
     * @param context
     * @return
     */
    private PackageInfo getPackageInfo(Context context) {
        PackageInfo pi;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new PackageInfo();
    }


    /**
     * 跳转谷歌下载
     *
     * @param context
     * @param appPkg  应用的包名
     */
    private void downloadApp(Context context, String appPkg) {
        final String GOOGLE_PLAY = "com.android.vending";//这里对应的是谷歌商店，跳转别的商店改成对应的即可
        try {
            if (TextUtils.isEmpty(appPkg))
                return;
            Uri uri = Uri.parse("market://details?id=" + appPkg);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setPackage(GOOGLE_PLAY);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            //Toast.makeText(context, "", Toast.LENGTH_SHORT).show();   //跳转失败的处理
        }
    }

    /**
     * 获取版本
     *
     * @param activity
     * @return
     */
    public String getVersion(Activity activity) {
        try {
            PackageInfo packageInfo = getPackageInfo(activity);
            return packageInfo.versionName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 更新已阅读消息
     *
     * @param notification_id
     * @param notification_type
     */
    public void readNotifacation(int notification_id, String notification_type) {
        baseSubscribe(apiService.readNotification(UserInfo.getMemberId(), notification_id, notification_type),
                new NetParams(false, false, false),
                resultModel -> {
                });
    }
}